<?php

namespace app\sapi\controller\v1;


use app\common\controller\Api;
use addons\third\library\Service;
use addons\third\model\Third;
use app\admin\model\Admin;
use app\admin\model\Shop;
use app\admin\model\ShopFollow;
use app\admin\model\ShopPlatform;
use app\common\model\Config as configs;
use app\common\model\User as UserModel;
use app\common\model\UserShareImage;
use app\common\library\Image;
use fast\Random;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;
use app\admin\model\AdminLog;
use think\Validate;


// use think\Request;
use wechat\AccessToken;
use wechat\Wechat;


/**
 * 商家
 * Class Business
 * @package app\sapi\controller\v1
 */
class Business extends Api
{
    protected $noNeedLogin = ['getApplyParam','login','addShop','jdId','wxOfficialAccountBaseLogin'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        //监听登录成功的事件
        Hook::add('business_login_successed', function ($shop) use ($auth) {

        });
        //监听退出登陆的事件
        Hook::add('business_logout_successed', function ($shop) use ($auth) {

        });
    }


    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success('退出成功', null, 200);
    }

    /**
     * 获取商家信息
     */
    public function info()
    {
        // $user = (new UserModel())->where(['id' => $this->auth->id,'user_type'=>1])->find();
        $user = (new UserModel())->where(['id' => $this->auth->id])->find();
        if (empty($user)) $this->error('商家不存在');
        $user['token'] = $this->auth->getToken();
        $user['bio'] = Shop::where(['have_uid'=>$user['id'],'shop_status'=>1])->limit(3)->select();
        //今日订单量
        $time0 = strtotime(date("Y-m-d", time()));
        $time24 = $time0 + 86400;

        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => ['=', $this->auth->id],
        //     'place_time' => ['between', [$time0, $time24]]
        // ])
        //     ->count();
        // $totalMoney = (new BusinessWalletLog())->where([
        //     'business_id' => ['=', $this->auth->id],
        //     'createtime' => ['between', [$time0, $time24]],
        //     'wallet' => ['<', 0],
        //     'wallet_type' => ['=', 2]
        // ])
        //     ->sum('wallet');
        // $businessInfo['today_order_num'] = $orderNum;
        // $businessInfo['today_total_money'] = abs($totalMoney);
        $this->success('商家信息', $user);
    }

    /**
     * h5登录
     * @DateTime 2023-04-20T15:21:15+0800
     * @return   [type]                   [description]
     */
    public function wxOfficialAccountBaseLogin()
    {
        $platform = $this->request->post("platform", 'wechat');
        $code = input('code');
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $platformObj = $app->{$platform};
        $result = $platformObj->getAccessToken($code);
            // var_dump($result);exit;
        $openid = $result['openid'];
        if (empty($openid)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        try {
            $wechatUserInfo = $platformObj->getUserInfo($result);
            // \think\Log::write('商户h5微信信息:'.json_encode($wechatUserInfo,JSON_UNESCAPED_UNICODE));
            // $unionid = isset($wechatUserInfo['userinfo']['unionid'])?$wechatUserInfo['userinfo']['unionid']:'';
            $user = (new UserModel())->where(['openid' => $openid,'user_type'=>1,'status'=>'normal'])->find();
            // var_dump($user);exit;
            if (isset($user) && $user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $username = getUniqueUsername();
                $extend = [
                    'openid' => $openid,
                    'nickname' => $wechatUserInfo['userinfo']['nickname'] ?? '微信用户',
                    'avatar' => $wechatUserInfo['userinfo']['avatar'] ?? "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
                    'gender' => 0,
                    'pid' => input('pid/d', 0),
                    'unionid' => '',
                    'user_type' => 1
                ];
                $ret = $this->auth->register($username, Random::alnum(), '', '', $extend);
            }
            //用户注册成功
            if ($ret) {
                $userInfo = (new UserModel())->where('id', $this->auth->id)->find();
                $userWechat = (new Third())->where(['user_id' => $userInfo['id'], 'openid' => $openid])->find();
                if (!$userWechat) {
                    $data = $userInfo->toArray();
                    //微信用户表添加记录
                    $data['platform'] = 'h5';
                    $data['user_id'] = $data['id'];
                    $data['openid'] = $openid;
                    $data['access_token'] = '';
                    $data['refresh_token'] = '';
                    $data['expires_in'] = 3600 * 24 * 7;
                    $data['unionid'] = $unionid ?? '';
                    unset($data['id']);
                    Service::connect('wechat', $data);
                }
                $userInfo = $this->auth->getUserinfo();
                $userInfo['session_key'] = '';
                Db::commit();
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                Db::rollback();
                $this->error($this->auth->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            \think\Log::write('商户h5:'.$e->getMessage());
            $this->error('登陆失败');
        }
        $this->success('', $data);
    }

    /**
     * 店铺列表
     * @DateTime 2023-03-22T10:23:56+0800
     * @return   [type]                   [description]
     */
    public function shopList()
    {
        $shop_no = input('shop_no','');
        $page = input('page/d',1);
        $page_num = 100;
        $list = [];
        $total_page = 0;
        $total = 0;
        if ($shop_no) {
            $phone = Db::name('shop')->where('shop_no',$shop_no)->value('phone');
            if ($phone) {
                $where = ['phone'=>$phone];
                $list = Shop::where($where)->with(['platform'])->page($page,$page_num)->select();
                foreach ($list as $key => $value) {
                    $value->getRelation('platform')->visible(['qrcode_pic','platform_no']);
                }
                $total = Shop::where($where)->count();
                $total_page = ceil($total/$page_num);
            } else {
                $where = ['shop_no'=>$shop_no];
                $list = Shop::where($where)->with(['platform'])->page($page,$page_num)->select();
                foreach ($list as $key => $value) {
                    $value->getRelation('platform')->visible(['qrcode_pic','platform_no']);
                }
                $total = Shop::where($where)->count();
                $total_page = ceil($total/$page_num);
            }
        }
        $this->success('店铺列表', ['list'=>$list,'total_page'=>$total_page,'total'=>$total]);


        // $shop_status = input('shop_status/d',9);//9表示全部
        // $page = input('page/d',1);
        // $page_num = 100;
        // if ($this->auth->user_type!=1) {
        //     $this->error('您不是商家');
        // }
        // $user_id = $this->auth->id;
        // $list = [];
        // $total_page = 0;
        // $total = 0;
        // if ($this->auth->mobile) {
        //     // 查询是不是中间人，如果是中间人查询中间人介绍的店铺
        //     // $middleman = Db::name('middleman')->where('user_id',$user_id+config('virtual_userid'))->find();
        //     // if ($middleman) {
        //     //     $where = ['shop_status'=>['>=',0]];
        //     //     $where['middleman_id'] = ['=',$middleman['id']];
        //     //     if ($shop_status!=9) {
        //     //         $where['shop_status'] = ['=',$shop_status];
        //     //     }
        //     //     $where['delete_dt'] = ['null',''];
        //     // } else {
        //         $where = ['shop_status'=>['>=',0]];
        //         $where['phone'] = ['=',$this->auth->mobile];
        //         if ($shop_status!=9) {
        //             $where['shop_status'] = ['=',$shop_status];
        //         }
        //         $where['delete_dt'] = ['null',''];
        //     // }
        //     $list = Shop::where($where)->with(['platform'])->page($page,$page_num)->select();
        //     foreach ($list as $key => $value) {
        //         $value->getRelation('platform')->visible(['qrcode_pic','platform_no']);
        //     }
        //     $total = Shop::where($where)->count();
        //     $total_page = ceil($total/$page_num);
        // }
        // $this->success('店铺列表', ['list'=>$list,'total_page'=>$total_page,'total'=>$total]);
    }

    /**
     * 店铺详细
     * @DateTime 2023-03-22T10:38:28+0800
     * @return   [type]                   [description]
     */
    public function shopDetail()
    {
        $id = input('id/d', 0);
        if (!$id) {
            $this->error('缺少参数');
        }
        $where = [];
        $where['s.have_uid'] = ['=',$this->auth->id];
        $where['s.shop_status'] = ['=',1];
        $where['s.delete_dt'] = ['null',''];
        $where['s.id'] = ['=',$id];
        $info = Shop::where($where)->alias('s')->field('s.*,sp.qrcode_pic,sp.qrcode_pic as qrcode_pic_url,sp.platform_no')->join('chbc_shop_platform sp','sp.shop_no=s.shop_no')->find();
        $info['qrcode_pic_url'] = config('upload_domain').$info['qrcode_pic_url'];
        $this->success('店铺详情', $info);
    }

    public function update()
    {
        $nickName = input('nickName', '','htmlspecialchars');
        $avatarUrl = input('avatarUrl', '','htmlspecialchars');
        $data = ['updatetime' => time()];
        if ($nickName != '') $data['nickname'] = $nickName;
        if ($avatarUrl != '') $data['avatar'] = $avatarUrl;
        try {
            $user = (new \app\common\model\User())->where(['id' => $this->auth->id])->find();
            $res = $user->allowField(true)
                ->isUpdate(true)
                ->save($data);
            if (!$res) $this->error('更新失败');
            $this->success('更新成功', $res);
        } catch (Exception $exception) {
            $this->error('更新失败');
        }
    }

    /**
     * [getApplyParam 获取店铺分类和营业时间选项参数]
     * @DateTime 2023-03-18T18:07:29+0800
     * @return   [type]                   [description]
     */
    public function getApplyParam()
    {
        $business_time = configs::getConfigs('business_time',2);
        $shop_category = configs::getConfigs('shop_category',2);
        $shop_type = config('shop_type');
        $this->success('成功',['business_time'=>$business_time,'shop_category'=>$shop_category,'shop_type'=>$shop_type]);
    }

    /**
     * 修改商家信息
     * @param ManystoreShop $manystoreShop
     */
    public function EditShopInfo(Business $business)
    {
        $shopId = SHOP_ID;
//        $mobile = input('mobile/d', '');
//        $shopName = input('shop_name', '');
        $shopName = input('shop_name', '');
        $addressName = input('address_name', '');//位置名称
        $address = input('address', '');//地图详细地址
        $addressDetail = input('address_detail', '');//用户补充地址
        $latitude = input('latitude', '');//维度
        $longitude = input('longitude', '');//经度
        if (trim($shopName) == '') {
            $this->error('请填写商家名称' . $shopName, null, 400);
        }
        $data = [
            'name' => $shopName,
//            'address' => $addressName,
//            'address_detail' => $address . $addressDetail,
//            'latitude' => $latitude,
//            'longitude' => $longitude,
//            'tel' => $mobile,
        ];
        $res = $business->updateShopInfo($shopId, $data);
        if ($res)
            $this->success('操作成功', null, 200);
        else
            $this->error('操作失败', null, 400);
    }

    public function setOpenid()
    {
        $code = input('code', '');
        $shopId = SHOP_ID;
        $miniConfig = Config::get('shop_mini');
        $manystore = (new Business())->where('shop_id', $shopId)->find();
        if (empty($manystore) || $shopId <= 0 || empty($miniConfig) || trim($code) == '') {
            $this->error('设置失败', null, 400);
        }
        $wechat = new Wechat($miniConfig['appid'], $miniConfig['appsecret']);
        $wechatUserInfo = $wechat->code2Session($code);
        if (isset($wechatUserInfo['errcode']) && $wechatUserInfo['errcode'] !== 0) {
            $this->error('设置失败', null, 400);
        }
        $manystore->wx_openid = $wechatUserInfo['openid'];
        $res = $manystore->save();
        if ($res || $manystore->wx_openid == $wechatUserInfo['openid']) {
            Cache::store('redis')->set($shopId . "_message_status_token", $this->token);
            $this->success('设置成功', null, 200);
        } else {
            $this->error('设置失败', null, 400);
        }
    }

    /**
     * 重置密码
     */
    public function resetPassword()
    {
        $mobile = input('mobile');//手机号
        $captcha = input('captcha');//验证码
        $password = input('password');//密码
        $rule = [
            'mobile' => 'require|number|max:11|regex:^1\d{10}$',
            'captcha' => 'require|number|length:4',
            'password' => 'require|alphaDash|length:6,16'
        ];
        $message = [
            'mobile.require' => '手机号必须填写',
            'mobile.number' => '手机号必须是数字',
            'mobile.max' => '手机号不能超过11位',
            'mobile.regex' => '手机号格式错误',
            'captcha.require' => '验证码必须填写',
            'captcha.number' => '验证码必须是数字',
            'captcha.length' => '验证码长度错误',
            'password.require' => '密码必须填写',
            'password.alphaDash' => '密码只能是数字、字母、_-',
            'password.length' => '密码长度为6-16位',
        ];
        $data = [
            'mobile' => $mobile,
            'captcha' => $captcha,
            'password' => $password
        ];
        $res = $this->validate($data, $rule, $message);
        if (true !== $res) {
            // 验证失败 输出错误信息
            $this->error($res, null, 422);
        }
        /*$shopInfo = ManystoreShop::getByTel($mobile);
        if (empty($shopInfo) || $shopInfo['status'] != 1)
            $this->error('商家手机号不存在', null, 404);
        $shopAccount = Manystore::getByShopId($shopInfo['id']);
        if (empty($shopAccount) || $shopAccount['status'] != 'normal')
            $this->error('商家账号异常', null, 404);
        $salt = Random::alnum();
        $shopAccount->salt = $salt;
        $shopAccount->password = md5(md5($password) . $salt);
        $res = $shopAccount->isUpdate(true)->save();
        if ($res)
            $this->success('重置成功');
        else
            $this->error('重置失败', null, 400);*/
    }


    /**
     * 自动上店
     * @DateTime 2023-04-04T18:13:00+0800
     * @return   [type]                   [description]
     */
    public function addShop()
    {
        // 权限
        if (!isset($_SERVER['HTTP_TOKEN']) || !$_SERVER['HTTP_TOKEN']) {
            echo json_encode(['code'=>401,'msg'=>'please login first']);exit;
        }
        // 过期时间一周
        $time = substr($_SERVER['HTTP_TOKEN'],-10);
        if ($time+604800<time()) {
            echo json_encode(['code'=>401,'msg'=>'please login first']);exit;
        }
        $admin = Db::name('admin')->where('token',$_SERVER['HTTP_TOKEN'])->find();
        if (!$admin) {
            echo json_encode(['code'=>401,'msg'=>'please login first']);exit;
        }
        if (!Db::name('auth_group_access')->where('uid='.$admin['id'].' and group_id in (1,3)')->find()) {
            $this->error('错误的角色组');
        }
        // 上店
        $data = [
            'shop_type' => input('shop_type/d', 0),
            'shop_name' => input('shop_name', '','htmlspecialchars'),
            'phone' => input('phone', '','htmlspecialchars'),
            'address' => input('address', '','htmlspecialchars'),
            'logo_pic' => input('logo_pic', '','htmlspecialchars'),
            'business_time' => input('business_time'),
            'platform_no' => input('platform_no', '','htmlspecialchars'),
            'is_sjzp' => input('is_sjzp', '','htmlspecialchars'),
            'venderId' => input('venderId', '','htmlspecialchars'),
            'poi_id_str' => input('poi_id_str', '','htmlspecialchars'),
            'elm_appenter' => input('elm_appenter', '','htmlspecialchars'),
            'is_xls' => input('is_xls', '','htmlspecialchars'),
            'sku' => input('sku', '','htmlspecialchars'),
            'score' => input('score', '','htmlspecialchars'),
            'sales_volume' => input('sales_volume', '','htmlspecialchars'),
            'salesman_admin_id' => $admin['id'],
        ];
        $data['sku'] = str_replace('\\', '"', $data['sku']);
        if (!in_array($data['shop_type'], [1,2,3])) {
            $this->error('店铺类型有误');
        }
        $rule = [
            'shop_type' => "require",
            'shop_name' => "require",
            'logo_pic' => "require",
            // 'phone' => "require",
            // 'business_time' => "require",
            'address' => "max:500",
            'platform_no' => "require|max:150",
            'is_sjzp' => "require",
            'is_xls' => "require",
        ];
        $msg = [
            'shop_type.require' => '店铺类型有误',
            'shop_name.require' => '请填写店铺名称',
            // 'shop_name.max' => '店铺名称为2到15个字',
            'logo_pic.require' => '请上传logo',
            // 'logo_pic.max' => '请上传logo',
            // 'phone.require' => '请填写手机号',
            // 'address.require' => '请填写地址',
            'address.max' => '地址过长',
            // 'business_time.require' => '请上传营业时间',
            'platform_no.require' => '请上传店铺ID',
            'is_sjzp.require' => '请上传配送方式',
            'is_xls.require' => '请上传新零售字段',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) $this->error($validate->getError());
        if (($data['shop_type']==3 && !isset($data['venderId'])) || ($data['shop_type']==2 && !isset($data['elm_appenter'])) || ($data['shop_type']==1 && !isset($data['poi_id_str']))) {
            $this->error('缺少必要参数');
        }
        $platform_no = $data['platform_no'];
        $is_xls = $data['is_xls'];
        unset($data['platform_no']);
        unset($data['is_xls']);
        // 营业时间
        if (!$data['business_time']) {
            $data['business_time'] = '[{"start":"00:00","end":"23:59"}]';
        } else {
            if (strpos($data['business_time'],'，')!==false) {
                $arr2 = explode('，', $data['business_time']);
                $arr4 = [];
                foreach ($arr2 as $v) {
                    $arr3 = explode('-', $v);
                    $arr4[] = $arr3[0];
                    $arr4[] = $arr3[1];
                }
                $end = end($arr4);
                if (strpos($end,'次日')!==false || $end=='00:00' || $end=='24:00') $end = '23:59';
                $data['business_time'] = '[{"start":"'.$arr4[0].'","end":"'.$end.'"}]';
            } elseif (strpos($data['business_time'],',')!==false) {
                $arr2 = explode(',', $data['business_time']);
                $arr4 = [];
                foreach ($arr2 as $v) {
                    $arr3 = explode('-', $v);
                    $arr4[] = $arr3[0];
                    $arr4[] = $arr3[1];
                }
                $end = end($arr4);
                if (strpos($end,'次日')!==false || $end=='00:00' || $end=='24:00') $end = '23:59';
                $data['business_time'] = '[{"start":"'.$arr4[0].'","end":"'.$end.'"}]';
            } else {
                $arr = explode('-', $data['business_time']);
                if (isset($arr[0]) && isset($arr[1])) {
                    if (strpos($arr[1],'次日')!==false || $arr[1]=='00:00' || $arr[1]=='24:00') $arr[1] = '23:59';
                    $data['business_time'] = '[{"start":"'.$arr[0].'","end":"'.$arr[1].'"}]';
                } else {
                    $data['business_time'] = '[{"start":"00:00","end":"23:59"}]';
                }
            }
        }
        // 地址
        if ($data['address']) {
            $data['address'] = str_replace(' ', '', $data['address']);
            $area = $this->getArea($data['address']);
            $area['province'] = str_replace('市', '', $area['province']);
            $data = array_merge($data,$area);
            $data['shop_area'] = implode('/', $area);
            // 经纬度
            $config = get_addon_config('address');
            $maptype = $config['maptype'];
            $res = file_get_contents("https://apis.map.qq.com/ws/geocoder/v1/?address=".$data['address']."&output=json&key=".$config[$maptype . 'key']);
            $decode = json_decode($res,1);
            if (isset($decode['status']) && $decode['status']==0) {
                $data['lng']=$decode['result']['location']['lng'];
                $data['lat']=$decode['result']['location']['lat'];
            }
        }
        // logo处理
        $picposition = strpos($data['logo_pic'],'?');
        if ($picposition!==false) {
            $data['logo_pic'] = substr($data['logo_pic'],0, -1*$picposition);
        }
        $picposition = strpos($data['logo_pic'],'@130w');
        if ($picposition!==false) {
            $data['logo_pic'] = str_replace('@130w', '', $data['logo_pic']);
        }
        $picposition = strpos($data['logo_pic'],'s192x192_');
        if ($picposition!==false) {
            $data['logo_pic'] = str_replace('s192x192_', '', $data['logo_pic']);
        }
        // 店铺ID
        if ($data['shop_type']==3) {
            $venderId = $data['venderId'];
            $appId = 'B594E1702946F919D4B3B9C0DA5B4985';
            $text = sprintf('https://mini-app-static.jd.com/apps/mpshare/index.html?category=jump&des=jdmp&vapptype=1&appId=%s&param={"storeId":"%s","venderId":"%s","source":"qrCode","skuId":""}',$appId,$platform_no,$venderId);
            $elm_appenter = sprintf('https://hour.jd.com/msstore/index?venderId=%s&storeId=%s&launchChannel=JDJL',$venderId,$platform_no);
            $platform_no = '?bizType=1&venderId='.$venderId.'&storeId='.$platform_no.'&appId='.$appId;
        } elseif ($data['shop_type']==2) {
            if ($is_xls) {
                // $text = 'https://h5-newretail.faas.ele.me/static/h5_newretail/pages/shop.html?isTransfer=1&store_id='.$platform_no.'&*from=seller_domain.shop_setup.shop_qrcode_share';
                $text = 'https://h5-newretail.faas.ele.me/static/h5_newretail/pages/shop.html?isTransfer=1&store_id='.$platform_no.'&*from=seller_domain.shop_setup.shop_qrcode_share';
            } else {// 饿了么餐饮，扫码时$data['elm_appenter']有值，否则没有值
                $text = $data['elm_appenter'];
            }
            $elm_appenter = $data['elm_appenter'];
        } elseif ($data['shop_type']==1) {
            if ($data['poi_id_str']) {
                $platform_no = $data['poi_id_str'];
                $text = 'https://h5.waimai.meituan.com/waimai/mindex/menu?mtShopId=-100&poi_id_str='.$platform_no;
            } else {
                $text = 'https://h5.waimai.meituan.com/waimai/mindex/menu?mtShopId='.$platform_no.'&poi_id_str=';
            }
            // $text = 'https://i.waimai.meituan.com/external/poi/'.$platform_no;
            $elm_appenter = $data['poi_id_str'];
        }
        unset($data['venderId']);
        unset($data['poi_id_str']);
        unset($data['elm_appenter']);
        // 判断同一店铺:
        // 平台相同、店铺ID相同:针对美团、京东、饿了么零售
        // 平台相同、APP进店URL相同:针对饿了么餐饮;
        $data['shop_name'] = trim($data['shop_name']);
        $model = Shop::where(['shop_type'=>$data['shop_type'],'shop_name'=>$data['shop_name'],'address' => $data['address'],'shop_status'=>['>=',0]])->find();
        if (!$model) {
            if ($data['shop_type']==2 && !$is_xls) {
                $one = Db::name('shop_platform')->where(['elm_appenter'=>$elm_appenter])->find();
            } else {
                $one = Db::name('shop_platform')->where(['platform_no'=>$platform_no])->find();
            }
            if ($one) {
                $model = Shop::where(['shop_no'=>$one['shop_no'],'shop_status'=>['>=',0]])->find();
            }
        }
        if (!isset($model) || !$model) {
            $is_update = 0;
            $model = new Shop();
            $save = $data;
            $save['shop_no'] = $this->generateNo(['biz_tag'=>'shop_no','len'=>10,'int_prefix'=>1]);
            $save['shop_status'] = 0;
            // 同名店铺(店铺名相同，店铺地址不同)   需要在店铺名之后加个尾巴 -address
            // $repeatshop = Shop::where(['shop_type'=>$data['shop_type'],'shop_name'=>$data['shop_name']])->find();
            // if ($repeatshop) {
            //     $save['shop_name'] = $data['shop_name'] = $data['shop_name'].'-'.$data['address'];
            //     // 如果存在同名店铺(店铺名相同，店铺地址不同)，再查一下有没有名称是店铺+地址的
            //     $repeatshop2 = Shop::where(['shop_type'=>$data['shop_type'],'shop_name'=>$data['shop_name']])->find();
            //     if ($repeatshop2) {
            //         $model = $repeatshop2;
            //         $is_update = 1;
            //     }
            // }
        } else {
            unset($data['phone']);
            unset($data['shop_area']);
            unset($data['province']);
            unset($data['city']);
            unset($data['area']);
            unset($data['salesman_admin_id']);
            // 同名店铺(店铺名相同，店铺地址不同)   需要在店铺名之后加个尾巴 -address
            // if (Shop::where('shop_type='.$data['shop_type'].' and shop_name="'.$data['shop_name'].'" and id<>'.$model['id'])->find()) {
            //     $data['shop_name'] = $data['shop_name'].'-'.$data['address'];
            // }
            $save = $data;
            // $save['shop_status'] = 0;
            $is_update = 1;
        }
        // 生成店铺二维码
        $qrcode_pic = '';
        if ($text && (!$is_update || ($is_update && $data['shop_type']==2 && !$is_xls))) {
            $config = get_addon_config('qrcode');
            $params = array_intersect_key($config, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
            $params['logo'] = 0;
            $params['padding'] = 10;
            $params['text'] = $text;
            $params['label'] = $config['label'];

            $qrCode = \addons\qrcode\library\Service::qrcode($params);

            $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

            // 写入到文件
            $dirPath = '/uploads/platformqrcode/';
            $qrcodePath = UPLOADS_PATH . $dirPath;
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $imgName = md5(implode('', $params)) . '.' . $config['format'];
                $filePath = $qrcodePath . $imgName;
                $qrCode->writeFile($filePath);
                $qrcode_pic = config('domain') . $dirPath . $imgName;
            }
        }
        $return = [];
        Db::startTrans();
        // try {
            $result = $model->allowField(true)->save($save);
            $return = $model['id'];
            $updatedata = [
                'shop_no'=>$model['shop_no'],
                // 'qrcode_pic'=>$qrcode_pic,
                'is_xls'=>$is_xls,
            ];
            if (isset($data['sku']) && $data['sku']) {
                $updatedata['sku'] = $data['sku'];
            }
            // 平台信息，更新店铺信息时，除了饿了么餐饮店铺需要更新店铺ID，其他类型的店铺ID、APP进店都不需要更新
            if (!$is_update || ($is_update && $data['shop_type']==2 && !$is_xls)) {
                $updatedata['platform_no'] = $platform_no;
                $updatedata['elm_appenter'] = $elm_appenter;
                $updatedata['qrcode_pic'] = $qrcode_pic;
            }
            $sp = ShopPlatform::where([
                'shop_no' => $model['shop_no'],
            ])->find();
            if (!$sp) {
                $sp = new ShopPlatform();
                $sp->save($updatedata);
            } else {
                if ($platform_no!=$sp['platform_no']) {
                    $sp->save($updatedata);
                }
            }
            // 默认手续费
            $shop_serviceamt = Db::name('shop_serviceamt')->where('shop_no',$model['shop_no'])->find();
            if (!$shop_serviceamt) {
                $channels = Db::name('channel')->where('status',1)->select();
                $channel = [];
                foreach ($channels as $key => $value) {
                    $channel[$key]['channel_id'] = $value['id'];
                    $channel[$key]['channel_name'] = $value['name'];
                    $channel[$key]['service_amt'] = (float)$value['service_amt'];
                    $channel[$key]['shop_no'] = $model['shop_no'];
                }
                Db::name('shop_serviceamt')->insertAll($channel);
            }
            // 标记同名店铺
            $count = Db::name('shop')->where(['shop_type'=>$data['shop_type'],'shop_name'=>$data['shop_name'],'shop_status'=>['>=',0]])->count();
            if ($count>1) {
                Db::name('shop')->where(['shop_type'=>$data['shop_type'],'shop_name'=>$data['shop_name'],'shop_status'=>['>=',0]])->update(['same_name'=>1,'update_dt'=>date('Y-m-d H:i:s')]);
            }
            Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     \think\Log::write($_SERVER['REQUEST_URI'].'=>Exception:'.$e->getMessage());
        //     $this->error('店铺提交失败');

        // }
        if ($is_update) {
            $this->success('更新成功，店铺ID为'.$return,$return);
        } else {
            $this->success('上店成功',$return);
        }
    }


    public function getArea($address)
    {        
        if (substr_count($address, '市') == 2) {
            $regular = '/(.*?(区|县|镇|乡|街道|市))/';
        } else {
            $regular = '/(.*?(区|县|镇|乡|街道))/';
        }
 
        preg_match('/(.*?(省|自治区))/', $address, $matches);
        if (count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = str_replace($province, '', $address);
            preg_match('/(.*?(市|自治州|地区|区划|县|城区))/', $address, $matches);
            if (count($matches) > 1) {
                $city = $matches[count($matches) - 2];
                $address = str_replace($city, '', $address);
            }
        } else {
            preg_match('/(.*?(北京市|天津市|重庆市|上海市|特别行政区))/', $address, $matches);
            if (count($matches) > 1) {
                $province = $matches[count($matches) - 2];
                $address = str_replace($province, '', $address);
            }
            preg_match('/(.*?(市|自治州|地区|区划|县|城区))/', $address, $matches);
            if (count($matches) > 1) {
                $city = $matches[count($matches) - 2];
                $address = str_replace($city, '', $address);
            } else {
                $city = isset($province) ? $province : '';
                $address = str_replace($city, '', $address);
            }
        }
        preg_match($regular, $address, $matches);
        if (count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area, '', $address);
        }
        $arr = [
            'province' => isset($province) ? $province : '',
            'city' => isset($city) ? $city : '',
            'area' => isset($area) ? $area : '',
        ];
        return $arr;
    }

    // 跟踪京东的短链接，跳转两次
    public function jdId()
    {
        $jdurl = input('jdurl','');
        if (!$jdurl) $this->error('传参有误');
        if (strpos($jdurl,'https://3.cn/')===false) $this->error('传参有误');
        $ch = curl_init($jdurl);
        curl_setopt_array($ch, [
            CURLOPT_FOLLOWLOCATION => false,   // 自动跟随 301/302
            CURLOPT_RETURNTRANSFER => true,   // 不输出内容
            CURLOPT_HEADER         => array('Accept:*/*','User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0','Connection: Keep-Alive'),  // 不需要头信息
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 5,
        ]);
        curl_setopt($ch, CURLOPT_HEADERFUNCTION,
            function($curl, $headerLine) use (&$header) {
                $header .= $headerLine;
                return strlen($headerLine);
            }
        );
        $res = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        if (isset($info['redirect_url']) && $info['redirect_url']) {
            $ch = curl_init($info['redirect_url']);
            curl_setopt_array($ch, [
                CURLOPT_FOLLOWLOCATION => false,   // 自动跟随 301/302
                CURLOPT_RETURNTRANSFER => true,   // 不输出内容
                CURLOPT_HEADER         => array('Accept:*/*','User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0','Connection: Keep-Alive'),  // 不需要头信息
                CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                CURLOPT_CONNECTTIMEOUT => 5,
                CURLOPT_TIMEOUT        => 5,
            ]);
            curl_setopt($ch, CURLOPT_HEADERFUNCTION,
                function($curl, $headerLine) use (&$header) {
                    $header .= $headerLine;
                    return strlen($headerLine);
                }
            );
            $res = curl_exec($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            if (isset($info['redirect_url']) && $info['redirect_url']) {
                $this->success('success',$info['redirect_url']);
            }
        }
        $this->error('获取参数失败');
    }


    // 上店用户登录
    public function login()
    {
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
            ];
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle('爆单宝上店登录');
            $admin = Admin::get(['username' => $username]);
            if (!$admin) {
                $this->error('用户名或密码不正确');
                return false;
            }
            if ($admin['status'] == 'hidden') {
                $this->error('用户状态异常，请联系客服');
                return false;
            }
            if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
                $this->error('登录错误，账号已锁定');
                return false;
            }
            if ($admin->password != md5(md5($password) . $admin->salt)) {
                $admin->loginfailure++;
                $admin->save();
                $this->error('用户名或密码不正确');
                return false;
            }
            if (!Db::name('auth_group_access')->where('uid='.$admin->id.' and group_id in (1,3)')->find()) {
                $this->error('错误的角色组');
            }
            $admin->loginfailure = 0;
            $admin->logintime = time();
            $admin->loginip = request()->ip();
            $admin->token = Random::uuid().time();
            $admin->save();
            \app\admin\model\AdminLog::record();
            $this->success(__('Login successful'), ['id' => $admin->id, 'username' => $username, 'avatar' => $admin->avatar,'token'=>$admin->token]);
        }
    }
}